package pkg

import (
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"os"
)

// HTTPHandle handle
type HTTPHandle struct {
	config  *Config
	message *Message
}

// NewHTTPHandle 创建HTTPHandle句柄
func NewHTTPHandle(c *Config, m *Message) *HTTPHandle {
	return &HTTPHandle{
		config:  c,
		message: m,
	}
}

// Response Response
func (p *HTTPHandle) Response(w http.ResponseWriter, code int) {
	s := p.message.Get(code)
	if 200 == code {
		w.Write([]byte(s))
	} else {
		w.Header().Set("message", s)
		w.WriteHeader(code)
	}
}

// Response1 Response1
func (p *HTTPHandle) Response1(w http.ResponseWriter, s string, code int) {
	if 200 == code {
		w.Write([]byte(s))
	} else {
		w.Header().Set("message", s)
		w.WriteHeader(code)
	}
}

const (
	//UploadHTML text
	UploadHTML = `<html> 
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>上传页面</title>
	<style>
	div{
		width: 500px;
		height: 100px;
		position: absolute;
		left: 50%;
		top: 50%;
		margin: -200px -500px -500px -250px;
	}
	</style>
</head>
<body>
	<div>
		<a href="/">文件列表</a>
		<hr />
		<form action="/upload" method="POST" enctype="multipart/form-data">
			保存文件名：<input type="text" name="name" value=""/>
			</br>
			上传文件：<input type="file" name="file" />
			<hr />
			<input type="submit" value="submit" />
		</form>
	</div>
</body>
</html>`
)

// ToUpload 跳转到上传页面
func (p *HTTPHandle) ToUpload(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(200)
	w.Header().Set("Context-Type", "text/html")
	w.Write([]byte(UploadHTML))
}

// DoUpload 处理上传请求
func (p *HTTPHandle) DoUpload(w http.ResponseWriter, r *http.Request) {
	err := r.ParseMultipartForm(p.config.MaxUploadSize())
	if err != nil {
		p.Response(w, 701)
		return
	}
	if r.MultipartForm == nil {
		p.Response(w, 702)
		return
	}

	fileName := "temp"
	if r.MultipartForm.Value != nil {
		names := r.MultipartForm.Value["name"]
		if len(names) > 0 {
			fileName = names[0]
		}
	}

	if r.MultipartForm.File == nil || len(r.MultipartForm.File) == 0 {
		p.Response(w, 703)
		return
	}
	err = p.saveFile(fileName, r, r.MultipartForm.File)
	if err == nil {

		fmt.Println("upload success:", fileName)
		p.Response1(w, fileName, 200)
	} else {
		p.Response1(w, err.Error(), 704)
	}
}

func (p *HTTPHandle) saveFile(fileName string, r *http.Request, formFiles map[string][]*multipart.FileHeader) error {
	for formName := range formFiles {
		formFile, _, _ := r.FormFile(formName)
		out, err := os.Create(p.config.Path + fileName)
		if err != nil {
			return err
		}
		defer out.Close()
		_, err = io.Copy(out, formFile)
		return err
	}
	return nil
}

// Delete 删除文件
func (p *HTTPHandle) Delete(w http.ResponseWriter, r *http.Request) {
	name := r.URL.Query().Get("name")
	if len(name) == 0 {
		p.Response(w, 705)
	} else {
		//删除文件
		err := os.Remove(p.config.Path + name)
		if err == nil {
			fmt.Println("delete file", name)
			p.Response(w, 200)
		} else {
			p.Response1(w, err.Error(), 706)
		}
	}
}
